//
//  HMTabBar.m
//  网易彩票01
//
//  Created by Macx on 16/2/19.
//  Copyright © 2016年 Macx. All rights reserved.
//

#import "HMTabBar.h"
#import "HMTabBarButton.h"
@interface HMTabBar ()
//用来记录选中的按钮
@property(nonatomic,weak)HMTabBarButton *selectedBtn;
@end

@implementation HMTabBar


-(void)addTabBarBtnWithNormalImg:(NSString *)normalImg andSelectedImg:(NSString *)selectedImg{
    HMTabBarButton *tabBarBtn=[[HMTabBarButton alloc]init];
    
    //setBackGroudImage而不是setImage
    [tabBarBtn setBackgroundImage:[UIImage imageNamed:normalImg] forState:UIControlStateNormal];
    [tabBarBtn setBackgroundImage:[UIImage imageNamed:selectedImg] forState:UIControlStateSelected];

    //添加监听事件
    [tabBarBtn addTarget:self action:@selector(tabBarBtnDidClick:) forControlEvents:UIControlEventTouchDown];
  //设置tag，
    tabBarBtn.tag=self.subviews.count;
    //设置第一个tabBarBtn为默认的选中状态
    if (self.subviews.count==0) {
        [self tabBarBtnDidClick:tabBarBtn];
    }
    
    //添加到tabBar上
    [self addSubview:tabBarBtn];
    
    
}

-(void)tabBarBtnDidClick:(HMTabBarButton *)tabBarBtn{
    if (self.selectedBtn==tabBarBtn) return;
    self.selectedBtn.selected=NO;
    self.selectedBtn=tabBarBtn;
    self.selectedBtn.selected=YES;
    
    //通知代理
    if ([self.delegate respondsToSelector:@selector(tabBar:didSelectBtn:)]) {
        [self.delegate tabBar:self didSelectBtn:tabBarBtn];
    }


}

-(void)layoutSubviews{
    [super layoutSubviews];
    CGFloat btnWidth=self.frame.size.width/self.subviews.count;
    CGFloat btnHeight=self.frame.size.height;
    
    //遍历计算出各个的frame；
    
    [self.subviews enumerateObjectsUsingBlock:^(__kindof UIButton * tabBarBtn, NSUInteger idx, BOOL * _Nonnull stop) {
       
        CGFloat btnX=idx*btnWidth;
        tabBarBtn.frame=CGRectMake(btnX, 0, btnWidth, btnHeight);
        
    }];


}
@end
